package normalsys.demo.base.token;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import normalsys.demo.base.config.Constant;
import normalsys.demo.base.util.string.StringUtil;
import org.apache.commons.lang.RandomStringUtils;

/**
* @author 作者 刘天宇
* @version 创建时间：2017年9月13日 上午11:13:42
* 功能 校验登录状态
*/
public class SessionKeyUtil {
	
	private SessionKeyUtil(){}
	
	//用来存储用户登录信息
	public static Map<String, SessionKey> userMap = new HashMap<>();

	/**
	 * 校验session是否失效
	 * @param req
	 * @return
	 */
	public static boolean isExpire(HttpServletRequest req) {
		String third_session = req.getHeader("third_session");
		if(null == userMap || !userMap.containsKey(third_session)) {//没登录过
			return true;
		}
		
		SessionKey sessionKey = userMap.get(third_session);
		
		return sessionKey.getCreate_time() + Constant.SESSION_KEY_EXPIRE_TIME < System.currentTimeMillis();
//		return false;
	}
	
	/**
	 * 获得unionid
	 * @param req
	 * @return
	 */
	public static String getUnionId(HttpServletRequest req) {
		String third_session = req.getHeader("third_session");
		SessionKey sessionKey = userMap.get(third_session);
		
		return sessionKey.getUnionid();
	}
	
	/**
	 * 获得openid
	 * @param req
	 * @return
	 */
	public static String getOpenid(HttpServletRequest req) {
		String third_session = req.getHeader("third_session");
		SessionKey sessionKey = userMap.get(third_session);
		
		return sessionKey.getOpenid();
//		return "okV_u0CFXiBu6d46PhMqKAlsvDN8";
	}
	
	/**
	 * 获得sessionKey
	 * @param req
	 * @return
	 */
	public static String getSessionKey(HttpServletRequest req) {
		String third_session = req.getHeader("third_session");
		SessionKey sessionKey = userMap.get(third_session);
		
		return sessionKey.getSession_key();
	}
	
	/**
	 * 缓存微信openId和session_key
	 * @param wxOpenId		微信用户唯一标识
	 * @param wxSessionKey	微信服务器会话密钥
	 * @param expires		会话有效期, 以秒为单位, 例如2592000代表会话有效期为30天
	 * @return
	 */
	public static String create3rdSession(String wxOpenId, String wxSessionKey, Long expires){
		String thirdSessionKey = RandomStringUtils.randomAlphanumeric(64);
		StringBuffer sb = new StringBuffer();
		sb.append(wxSessionKey).append("#").append(wxOpenId);
		
		//redisUtil.add(thirdSessionKey, expires, sb.toString());
		return thirdSessionKey;
	}

	public static boolean isExpire(String third_session) {
		if(StringUtil.isEmpty(third_session)) {
			return true;
		}
		if(null == userMap || !userMap.containsKey(third_session)) {//没登录过
			return true;
		}
		
		SessionKey sessionKey = userMap.get(third_session);
		
		return sessionKey.getCreate_time() + Constant.SESSION_KEY_EXPIRE_TIME < System.currentTimeMillis();
	}
}